<?php


namespace app\app\controller;


class Cangxiansheng extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    public function getType()
    {
        $list = n2db('zhibo_type')->where('is_show', 1)->order('sort', 'asc')->select();
        $cachekey = 'Cache_Cangxiansheng_zHibo_type_'.md5(\GuzzleHttp\json_encode($list));
        $cache = cache($cachekey);
        if(empty($cache)) {
            $typeIds = array_column($list, 'id');

            $subList = n2db('zhibo_sort_import')->alias('zsi')->join("zhibo_sort zs", "zs.import_name = zsi.name and zs.type_id = zsi.type_id", 'LEFT')->field('zsi.*,zs.num')->where(function ($query) {
                $query->whereNotNull('zs.import_name')->whereOr('zs.import_name', '<>', '');
            })->whereIn('zsi.type_id', $typeIds)->order('zsi.type_id', 'asc')->order('zsi.sort', 'asc')->select();
//        dump(db('zhibo_sort_import')->getLastSql());exit;
            foreach ($subList as $sub) {
                $index = array_search($sub['type_id'], $typeIds);
                $list[$index]['childs'][] = $sub;
            }
            foreach ($list as &$item) {


                if (!empty(trim($item['alias_name']))) {
                    $item['name'] = $item['alias_name'];
                }
                if(isset($item['childs'])) {

                    usort($item['childs'], function ($a, $b) {
                        if ($a['num'] == 0 && $b['num'] > 0) {
                            return 1;
                        }
                        return 0;
                    });
                }else{
                    $item['childs']=[];
                }
                array_unshift($item['childs'], [
                    "sort" => 0,
                    "game_id" => 0,
                    "type_id" => $sub['type_id'],
                    "name" => "全部"
                ]);
            }

            array_unshift($list,json_decode('{
              "alias_name": "广播",
              "sort": 0,
              "childs":[
                  {
                      "name":"全部",
                      "sort":0,
                      "game_id": 0,
                      "type_id": 0
                  }],
              "id": 24,
              "is_show": 1,
              "type": "guangbo",
              "name": "广播"
            }', true));
            array_unshift($list,json_decode('{
              "alias_name": "电视直播",
              "sort": 1,
              "childs":[
                  {
                      "name":"全部",
                      "sort":0,
                      "game_id": 0,
                      "type_id": 0
                  }],
              "id": 23,
              "is_show": 1,
              "type": "dianshi",
              "name": "电视直播"
            }', true));
            $cache = $list;
            cache($cachekey,$list, 60 * 60);
        }
        $this->success('获取成功', ['list' => $cache]);
    }
}